package com.moody.service.impl;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;

import javax.servlet.ServletContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.moody.hibernate.dao.CustInfoDAO;
import com.moody.hibernate.dao.OrgInfoDAO;
import com.moody.hibernate.dao.RightInfoDAO;
import com.moody.hibernate.dao.RoleInfoDAO;
import com.moody.hibernate.dao.RoleRightDAO;
import com.moody.hibernate.dao.UserInfoDAO;
import com.moody.hibernate.dao.UserRoleDAO;
import com.moody.hibernate.domain.CustInfo;
import com.moody.hibernate.domain.OrgInfo;
import com.moody.hibernate.domain.RightInfo;
import com.moody.hibernate.domain.RoleInfo;
import com.moody.hibernate.domain.RoleRight;
import com.moody.hibernate.domain.UserInfo;
import com.moody.hibernate.domain.UserRole;
import com.moody.service.SystemService;

@Service
public class SystemServiceImpl implements SystemService {
	private static final Logger log = LoggerFactory.getLogger(SystemServiceImpl.class);
	WebApplicationContext web = ContextLoader.getCurrentWebApplicationContext();
	ServletContext context = web.getServletContext();  
	WebApplicationContext ctx  = WebApplicationContextUtils.getWebApplicationContext(context);
	
	private OrgInfoDAO orgInfoDAO = OrgInfoDAO.getFromApplicationContext(ctx);
	private UserInfoDAO userInfoDAO = UserInfoDAO.getFromApplicationContext(ctx);
	private RoleInfoDAO roleInfoDAO = RoleInfoDAO.getFromApplicationContext(ctx);
	private RightInfoDAO rightInfoDAO = RightInfoDAO.getFromApplicationContext(ctx);
	private UserRoleDAO userRoleDAO = UserRoleDAO.getFromApplicationContext(ctx);
	private RoleRightDAO roleRightDAO = RoleRightDAO.getFromApplicationContext(ctx);
	private CustInfoDAO custInfoDAO = CustInfoDAO.getFromApplicationContext(ctx);
	
	public List<OrgInfo> findAllOrg() {
		return orgInfoDAO.findAll();
	}

	public OrgInfo findOrgById(String orgId) {
		return orgInfoDAO.findById(orgId);
	}

	public void deleteDebtById(String orgId) {
		orgInfoDAO.delete(orgInfoDAO.findById(orgId));
	}

	public void deleteOrgInfoById(String orgId) {
		orgInfoDAO.delete(orgInfoDAO.findById(orgId));
	}

	public void insertOrg(OrgInfo org) {
		orgInfoDAO.save(org);
	}

	public void updateOrg(OrgInfo org) {
		orgInfoDAO.update(org);
	}

	@SuppressWarnings("unchecked")
	public List<UserInfo> findAllUser() {
		return userInfoDAO.findAll();
	}

	public UserInfo findUserById(String userId) {
		return userInfoDAO.findById(userId);
	}

	public void deleteUserInfoById(String userId) {
		userInfoDAO.delete(userInfoDAO.findById(userId));
	}

	public void insertUser(UserInfo user) {
		userInfoDAO.save(user);
	}

	public void updateUser(UserInfo user) {
		//如果组织结构变化:更新cust_info.inputOrgId
		if(!user.getBelongorg().equals(userInfoDAO.findById(user.getUserId()).getBelongorg())){
			custInfoDAO.updateInputOrgIdByInputUserId(user.getUserId(), user.getBelongorg());
		}
		userInfoDAO.update(user);
		
	}

	@SuppressWarnings("unchecked")
	public List<RoleInfo> findAllRole() {
		return roleInfoDAO.findAll();
	}

	public void insertRole(RoleInfo role) {
		roleInfoDAO.save(role);
	}

	public void updateRole(RoleInfo role) {
		roleInfoDAO.update(role);
	}

	public RoleInfo findRoleById(String roleId) {
		return roleInfoDAO.findById(roleId);
	}

	public void deleteRoleInfoById(String roleId) {
		 roleInfoDAO.delete(roleInfoDAO.findById(roleId));
	}

	@SuppressWarnings("unchecked")
	public List<RightInfo> findAllRight() {
		return rightInfoDAO.findAll();
	}
	
	public void insertRight(RightInfo role) {
		rightInfoDAO.save(role);
	}

	public void updateRight(RightInfo role) {
		rightInfoDAO.update(role);
	}

	public RightInfo findRightById(String roleId) {
		return rightInfoDAO.findById(roleId);
	}

	public void deleteRightInfoById(String roleId) {
		rightInfoDAO.delete(rightInfoDAO.findById(roleId));
	}

	@SuppressWarnings("unchecked")
	public List<RoleInfo> findRoleByUserId(String userId) {
		List<UserRole> userRoleList = userRoleDAO.findByProperty("id.userId", userId);
		List<RoleInfo> roleList = new ArrayList<RoleInfo>();
		for(UserRole userRole : userRoleList){
			roleList.add(this.findRoleById(userRole.getId().getRoleId()));
		}
		return roleList;
	}

	public void deleteUserRoleByUserId(String userId) {
		userRoleDAO.deleteUserRoleByUserId(userId);
	}

	public void insertUserRole(List<UserRole> userRoleList) {
		userRoleDAO.insertUserRole(userRoleList);
	}
	
	@SuppressWarnings("unchecked")
	public List<UserRole> findUserRoleByUserId(String userId) {
		List<UserRole> userRoleList = userRoleDAO.findByProperty("id.userId", userId);

		return userRoleList;
	}

	@SuppressWarnings("unchecked")
	public List<RightInfo> findRightByRoleId(String roleId) {
		List<RoleRight> roleRightList = roleRightDAO.findByProperty("id.roleId", roleId);
		List<RightInfo> rightList = new ArrayList<RightInfo>();
		for(RoleRight roleRight : roleRightList){
			rightList.add(this.findRightById(roleRight.getId().getRightId()));
		}
		return rightList;
	}

	public void deleteRoleRightByUserId(String roleId) {
		roleRightDAO.deleteRoleRightByUserId(roleId);
	}
	
	@SuppressWarnings("unchecked")
	public List<RoleRight> findRoleRightByRoleId(String roleId) {	
		List<RoleRight> roleRightList = roleRightDAO.findByProperty("id.roleId", roleId);
		return roleRightList;
	}

	public void insertRoleRight(List<RoleRight> roleRightList) {
		roleRightDAO.insertRoleRight(roleRightList);
	}

	public UserInfo findLoginUser(String username, String password) {
		return userInfoDAO.findLoginUser(username,password);
	}

	public List<UserInfo> findLoginUserByUserName(String username) {
		return userInfoDAO.findLoginUserByUserName(username);
	}
	
	public boolean verifyUrlVisitRight(String url, String userId){
		if(url == null) return false;
		if(url.equals("/CRRS/")) return true; //登录页
		if(userId == null || userId.equals("")) return false;
		if(isCommonUrl(url))return true;
		
		List<String> urlList = rightInfoDAO.findAvailableUrlListByUserId(userId);
		if(urlList == null) return false;
		
		for(String availableUrl : urlList){
			StringTokenizer st = new StringTokenizer(availableUrl,";");
			while(st.hasMoreTokens()){
				String tempUrl = st.nextToken();
				if(url.contains(tempUrl))return true;
			}
		}
		return false;
		
	}
	
	public boolean isCommonUrl(String url){
		List<String> commonUrlList = new LinkedList<String>();
		commonUrlList.add("/CRRS/show"); //来自:CascadingControler
		commonUrlList.add("/CRRS/user/login.do"); //首页
		commonUrlList.add("/CRRS/view/Forbid.jsp"); //拒绝访问页
		
		for(String tempUrl : commonUrlList){
			if(url.contains(tempUrl))return true;
		}
		return false;
	}

	public List<UserInfo> findUserByIdOrUserName(String userId, String userName) {
		return userInfoDAO.findUserByIdOrUserName(userId,userName);
	}

	public List<UserInfo> findUserByCondition(Map<String, String> condition) {
		return userInfoDAO.findUserByCondition(condition);
	}
}
